<!--
 @description 启运近6月趋势
 @fileName ShipSixMonthChart.vue
 @author zengqiongying
 @created 2021/06/26 16:26:05
-->
<template>
  <div>
    <div class="trend-box">
      <div :id="chartId" ref="myEchart" class="echart_container" />
    </div>
  </div>
</template>

<script>
import ChartLineMixin from '@/mixins/ChartLine'
import { getSixMonthLogistics } from '@/apis/logistics'
export default {
  name: 'LogisticsChart',
  mixins: [ChartLineMixin],
  props: {
    selectType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      legendData: ['今年', '去年'], // 图列数据
      monthData: [],
      xAxisData: []
    }
  },
  created() {
    // this.initxAxisData()
  },
  methods: {
    initxAxisData() {
      const curYear = new Date().getFullYear()// 当年
      const curMonth = new Date().getMonth() + 1// 当月
      for (let i = curMonth - 5; i <= curMonth; i++) {
        const month = i < 1 ? 12 + i : i
        const monthTxt = month > 9 ? month : '0' + month
        // this.monthData.push(`${i < 1 ? curYear - 1 : curYear}-${monthTxt}`)
        this.monthData.push({ year: i < 1 ? curYear - 1 : curYear, month: monthTxt })
        this.xAxisData.push(`${monthTxt}月`)
      }
    },
    async getChartData() {
      const seriesData = []
      await getSixMonthLogistics().then(res => {
        if (res.data && res.data.length) {
          const groupDataList = []
          this.legendData.forEach(type => {
            // 根据图列类型分组: type = 今年/去年
            let item = res.data.filter(v => v.type === type)
            // 排序：date升序
            item = item.sort((a, b) => {
              return Number(a.date.replace(/-/g, '')) - Number(b.date.replace(/-/g, ''))
            })
            groupDataList.push(item)
          })
          const xAxisData = []
          groupDataList.forEach((item, i) => {
            const seriesItem = item.map(v => {
              if (i === 0) {
                const yearMonth = v.date.split('-')
                if (yearMonth.length === 2) {
                  xAxisData.push(yearMonth[1] + '月')
                }
              }
              return v.shipQuantity || 0
            })
            seriesData.push(seriesItem)
          })
          this.xAxisData = xAxisData

          /* const allData = res.data
          // 当前月份开始的最近6个月
          this.monthData.forEach(v => {
            const { year, month } = v
            const tmp1 = allData.find(item => item.date === `${year}-${month}`)
            seriesData[0].push((tmp1 && tmp1.shipQuantity) || 0)
            const tmp2 = allData.find(item => item.date === `${year - 1}-${month}`)
            seriesData[1].push((tmp2 && tmp2.shipQuantity) || 0)
          }) */
        }
      }).catch(err => {
        console.log(err)
      })
      this.chart.chartData = {
        xAxisData: this.xAxisData,
        seriesData
      }
    }
  }
}
</script>
<style lang='less' scoped>
  .trend-box{
    height: 240px;
  }
  .echart_container{
    height:240px
  }
</style>
